package com.heima.comment.service.impl;

import com.heima.aliyun.scan.GreenScan;
import com.heima.aliyun.scan.ScanResult;
import com.heima.comment.service.CommentHotService;
import com.heima.comment.service.CommentService;
import com.heima.common.exception.CustException;
import com.heima.common.exception.CustomException;
import com.heima.feigns.UserFeign;
import com.heima.model.comment.dtos.CommentDTO;
import com.heima.model.comment.dtos.CommentLikeDTO;
import com.heima.model.comment.dtos.CommentSaveDTO;
import com.heima.model.comment.pojos.ApComment;
import com.heima.model.comment.pojos.ApCommentLike;
import com.heima.model.comment.vos.ApCommentVo;
import com.heima.model.common.dtos.ResponseResult;
import com.heima.model.common.enums.AppHttpCodeEnum;
import com.heima.model.common.threadlocal.AppThreadLocalUtils;
import com.heima.model.user.pojos.ApUser;
import com.heima.model.wemedia.pojos.WmNews;
import lombok.extern.slf4j.Slf4j;
import org.redisson.api.RLock;
import org.redisson.api.RedissonClient;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Sort;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;

@Service
@Slf4j
public class CommentServiceImpl implements CommentService {
    @Autowired
    private UserFeign userFeign;

    @Autowired
    private GreenScan greenScan;
    @Autowired
    private MongoTemplate mongoTemplate;

    @Autowired
    private CommentHotService commentHotService;

    /**
     * 保存评论
     *
     * @return
     */

    @Override
    public ResponseResult saveComment(CommentSaveDTO dto) {
        if (dto.getArticleId() == null || dto.getContent() == null || "".equals(dto.getContent())) {
            CustException.cust(AppHttpCodeEnum.PARAM_INVALID);
        }
        ApUser user = AppThreadLocalUtils.getUser();
        if (user == null) {
            CustException.cust(AppHttpCodeEnum.NEED_LOGIN, "评论需要先登录");
        }
        //校验字符不能大于140个字符
        if (dto.getContent().length() > 140) {
            CustException.cust(AppHttpCodeEnum.PARAM_INVALID, "评论字数不能大于140字");
        }
        // 阿里云查询数据
        try {
            ScanResult scanResult = greenScan.greenTextScan(dto.getContent());
            String suggestion = scanResult.getSuggestion();
            switch (suggestion) {
                case "block":
                    // 失败
                    CustException.cust(AppHttpCodeEnum.DATA_NOT_ALLOW, "文章内容中包含违规词汇: " + scanResult.getLabel());
                    //  updateWmNews(WmNews.Status.FAIL.getCode(), "文章内容中包含违规词汇: " + scanResult.getLabel(), wmNews);
                    break;
                case "review":
                    // 人工
                    break;
                case "pass":
                    break;
                default:
                    break;
            }
        } catch (Exception e) {
            e.printStackTrace();
            CustException.cust(AppHttpCodeEnum.PARAM_INVALID, "校验出错");
        }

        //远程查询挡墙登陆用户信息
        ResponseResult<ApUser> user1 = userFeign.findUserById(user.getId());
        ApUser data = user1.getData();
        //创建评论信息,并保存到mongo
        ApComment comment = new ApComment();
        comment.setAuthorId(user.getId());
        comment.setAuthorName(data.getName());
        comment.setArticleId(dto.getArticleId());
        comment.setType((short) 0);
        // comment.setChannelId(data.);
        comment.setImage(data.getImage());
        comment.setCreatedTime(new Date());
        comment.setUpdatedTime(new Date());
        comment.setContent(dto.getContent());
        comment.setLikes(0);
        comment.setReply(0);
        mongoTemplate.save(comment);

        return ResponseResult.okResult();
    }

    @Autowired
    RedissonClient redisson;
    /**
     * 点赞评论
     *
     * @param dto
     * @return
     */
    @Override
    public ResponseResult like(CommentLikeDTO dto) {
        if (dto.getCommentId() == null || dto.getOperation() == null) {
            CustException.cust(AppHttpCodeEnum.PARAM_INVALID);
        }
        if (dto.getOperation().intValue() != 0 && dto.getOperation().intValue() != 1) {
            CustException.cust(AppHttpCodeEnum.PARAM_INVALID, "点赞方式只能为0或者1");
        }
        ApUser user = AppThreadLocalUtils.getUser();
        if (user == null) {
            CustException.cust(AppHttpCodeEnum.NEED_LOGIN, "点赞需要先登录");
        }
        Query query = Query.query(Criteria.where("id").is(dto.getCommentId()));
        ApComment apComment = mongoTemplate.findOne(query, ApComment.class);
        if (apComment == null) {
            CustException.cust(AppHttpCodeEnum.PARAM_INVALID, "查询不到评论信息");
        }
        //查询有没有点赞信息
        Query query2 = Query.query(Criteria.where("commentId").is(dto.getCommentId()).and("authorId").is(user.getId()));

        //获取锁

        RLock rlock = redisson.getLock("likes-lock");

        rlock.lock();  //代表加锁，加锁成功才会往下执行，否则阻塞
        ApCommentLike commentLike ;

        try {
            commentLike  = mongoTemplate.findOne(query2, ApCommentLike.class);
            //如果等于0说明是点赞信息
            if (dto.getOperation().intValue() == 0) {
                if (commentLike != null) {
                    CustException.cust(AppHttpCodeEnum.DATA_NOT_ALLOW, "请勿重复点赞");
                }
                ApCommentLike apCommentLike = new ApCommentLike();
                apCommentLike.setAuthorId(user.getId());
                apCommentLike.setCommentId(dto.getCommentId());
                apCommentLike.setOperation(dto.getOperation());
                mongoTemplate.save(apCommentLike);
                if (apComment.getLikes() == null) {
                    apComment.setLikes(1);
                } else {
                    apComment.setLikes(apComment.getLikes() + 1);
                }
                mongoTemplate.save(apComment);
                if (apComment.getLikes().intValue() >= 10 && apComment.getFlag().intValue() == 0) {
                    commentHotService.hotCommentExecutor(apComment);
                }
            }
            //取消点赞
            if (dto.getOperation().intValue() == 1) {
                if (commentLike == null) {
                    CustException.cust(AppHttpCodeEnum.DATA_NOT_ALLOW, "请先点赞");
                }
                mongoTemplate.remove(query2, ApCommentLike.class);
                if (apComment.getLikes() == null || apComment.getLikes() < 1) {
                    CustException.cust(AppHttpCodeEnum.DATA_NOT_ALLOW, "点赞数为0不能再减");
                }
                apComment.setLikes(apComment.getLikes() - 1);
                mongoTemplate.save(apComment);
            }
        } finally {
           rlock.unlock(); // 代表释放锁
        }

        HashMap<String, Integer> map = new HashMap<>();
        map.put("likes", apComment.getLikes());
        return ResponseResult.okResult(map);
    }

    /**
     * 根据文章id查询评论列表
     *
     * @return
     */
    @Override
    public ResponseResult findByArticleId(CommentDTO dto) {
        if (dto.getArticleId() == null) {
            CustException.cust(AppHttpCodeEnum.PARAM_INVALID);
        }
        if (dto.getSize() == null) {
            dto.setSize(10);
        }
        //未登录分页查询
        //根据文章id查询

        //分页
       /* int page = 0;
        int size = dto.getSize();
        if (dto.getIndex().intValue() == 1) {
            //说明是首页
            page = dto.getIndex().intValue() - 1;
        }else {
            size = dto.getIndex().intValue() * 10;
        }
        //  int page = (int) dto.getIndex();

        PageRequest request = PageRequest.of(page, size);
        query.with(request);*/
        List<ApComment> commentList = null;
        if(dto.getIndex().intValue() == 1){ // 判断当前是否是第一页评论
            // 先查询热点评论集合  （最多5条） (条件: flag=1, 文章id, 点赞降序)
            Query query = Query.query(Criteria.where("articleId").is(dto.getArticleId()).and("flag").is((short)1));
            //     1.1 按照文章id   flag=1(热点文章)   点赞降序
            Sort sort = Sort.by(Sort.Direction.DESC, "likes");
            query.with(sort);
            commentList = mongoTemplate.find(query, ApComment.class);


            // 新size = size - 热评数量
            int size = dto.getSize()- commentList.size();
            // 查询第一页剩余普通评论 (条件: 文章id, flag=0, 时间降序, limit:新size)
            Query query2 = Query.query(Criteria.where("articleId").is(dto.getArticleId()));
            query2.limit(size);
            Sort sort2 = Sort.by(Sort.Direction.DESC, "createdTime");
            query2.with(sort2);
            List<ApComment> apComments = mongoTemplate.find(query2, ApComment.class);


            // 合并 热点评论  普通评论   热点list.addAll(普通list)
            commentList.addAll(apComments);

        }else {
            Query query = Query.query(Criteria.where("articleId").is(dto.getArticleId()));
            query.skip((dto.getIndex().intValue() - 1) * dto.getSize());
            query.limit(10);

            //排序分局时间
            Sort sort = Sort.by(Sort.Direction.DESC, "createdTime");
            query.with(sort);

            commentList  = mongoTemplate.find(query, ApComment.class);
            // 不是第一页直接查询普通评论
            // (条件: 文章id,flag=0,createdTime小于最小时间,时间降序,limit:size)
        }


        // 如果登录了 需要检查在当前评论列表中 哪些评论登陆人点赞过
        ApUser user = AppThreadLocalUtils.getUser();

        if (user != null) {
            ArrayList<ApCommentVo> list = new ArrayList<>();

            for (ApComment apComment : commentList) {
                ApCommentVo apCommentVo = new ApCommentVo();
                Query query2 = Query.query(Criteria.where("authorId").is(user.getId()).and("commentId").is(apComment.getId()));
                ApCommentLike like = mongoTemplate.findOne(query2, ApCommentLike.class);
                if (like != null) {
                    BeanUtils.copyProperties(apComment, apCommentVo);
                    apCommentVo.setOperation((short) 0);
                } else {
                    BeanUtils.copyProperties(apComment, apCommentVo);
                }
                list.add(apCommentVo);
            }
            return ResponseResult.okResult(list);

        }

        return ResponseResult.okResult(commentList);
    }
}
